<?php
// +----------------------------------------------------------------------
// | Description: 客户
// +----------------------------------------------------------------------
// | Author: zl
// +----------------------------------------------------------------------

namespace app\crm\controller;

use app\admin\controller\ApiCommon;
use app\admin\model\PersonModel;
use app\admin\model\ShopModel;
use app\crm\model\BalanceLog;
use app\crm\model\Coupon;
use app\crm\model\CouponProvideCustomer;
use app\crm\model\CustomerAccount;
use app\crm\model\Setting;
use app\crm\model\SettingCategory;
use app\crm\model\Service;
use app\crm\model\ReturnVist;
use app\crm\model\ReturnVistT;
use app\crm\model\ReturnConsult;
use app\crm\model\Customer as CustomerModel;
use app\crm\model\ShopGoods;
use app\crm\model\TransferShop;
use app\mini\model\SysModelMini;
use app\crm\model\CustomerConfig as CustomerConfigModel;
use app\crm\model\CustomerGrade as CustomerGradeModel;
use app\mini\model\SysModelMiniCustomer;
use app\shop\model\Order;
use think\response\Json;
use think\facade\Db;
use Kingdee\Kingdee;
use app\crm\model\CustomerAccountLog;

class Customer extends ApiCommon
{
    protected $customerModel;
    protected $customerConfigModel;

    /**
     * 用于判断权限
     * @permission 无限制
     * @allow 登录用户可访问
     * @other 其他根据系统设置
     **/

    public function initialize()
    {
        $action = [
            'permission' => ['house_list','setcustomerage','setzycustomer','dsmonth','setmonth'],
            'allow' => ['users', 'info']
        ];
        event('CheckAuth',$action);
        $request = $this->request;
        $a = strtolower($request->action());

        $this->customerModel = new CustomerModel();
        $this->customerConfigModel = new CustomerConfigModel();
        if (!in_array($a, $action['permission'])) {
            parent::initialize();
        }
    }
    public function miniIndex(): Json
     {
        $res = Db::name('mini_index')->where('id',1)->find();

        return resultArray(['error' => '', 'data'=>['content'=>$res['wx_index']]]);
     }
     public function setMiniIndex(): Json
     {
        $param = request()->param();
        $content = $param['content'] ?? "";
        if(empty($content)){
            return resultArray(['error' => "内容不能为空"]);
        }
        $save['wx_index']        = $content;
        $save['update_time']    = time();
        $res = Db::name('mini_index')->where('id',1)->save($save);
        if(empty($content)){
            return resultArray(['error' => "保存失败"]);
        }
        return resultArray(['error' => '', 'data'=>[]]);
     }
     public function dsmonth()
     {

        // Db::name('customer_num')->insertAll($addNumAll);
        $save = [];
        $save['month1'] = 0;
        $save['month4'] = 0;


        Db::name('customer')->where('id','>',0)->update($save);
        $All = 0;
        $jisuanEnd = time();
        $time = 30*24*60*60;
        for ($i=1;$i<3;$i++){
            $bei = $i==1?1:4;
            $time = $time*$bei;
            $jisuanStr = $jisuanEnd-$time;

            // 获取某段时间之前成交的客户

            $jisuanWhere = [];
            array_push($jisuanWhere,['cj_time','<=',$jisuanStr]);
            array_push($jisuanWhere,['cj_time','>',0]);

            $custmerIdsChengjiao = Db::name("customer")->Where($jisuanWhere)->column('id');
            // 获取近*个月做过护理的客户
            $jisuanWhere = [];
            array_push($jisuanWhere,['create_time','>=',$jisuanStr]);
            array_push($jisuanWhere,['create_time','<=',$jisuanEnd]);
            $custmerIdsOne = Db::name("service_log")->Where($jisuanWhere)->column('customer_id');
            // 获取近*个月进店购买商品的客户
            $jisuanWhere = [];
            array_push($jisuanWhere,['deal_time','>=',$jisuanStr]);
            array_push($jisuanWhere,['deal_time','<=',$jisuanEnd]);
            array_push($jisuanWhere,['status','<>',4]);
            $custmerIdsTwo = Db::name("shop_order")->Where($jisuanWhere)->column('uid');
            // 获取近*个月进店充值、退款、退货的客户
            $jisuanWhere = [];
            array_push($jisuanWhere,['deal_time','>=',$jisuanStr]);
            array_push($jisuanWhere,['deal_time','<=',$jisuanEnd]);
            array_push($jisuanWhere,['status','<>',4]);
            $custmerIdsThree = Db::name("shop_refund_order")->Where($jisuanWhere)->column('uid');
            // 获取近*个月审核通过案例的客户
            $jisuanWhere = [];
            array_push($jisuanWhere,['tg_excellent_time','>=',$jisuanStr]);
            array_push($jisuanWhere,['tg_excellent_time','<=',$jisuanEnd]);
            $custmerIdsFour = Db::name("case")->Where($jisuanWhere)->column('customer_id');
            // 获取已经毕业的客户
            $jisuanWhere = [];
            array_push($jisuanWhere,['graduation_type','=',1]);
            $custmerIdsfive = Db::name("case")->Where($jisuanWhere)->column('customer_id');
            $zuizhongIds = array_merge($custmerIdsOne,$custmerIdsTwo,$custmerIdsThree,$custmerIdsFour,$custmerIdsfive);
            // 时间段内消费的客户
            $b = array_values(array_unique($zuizhongIds));
            // 时间段前成交的客户
            $a = $custmerIdsChengjiao;
            // 获取时间端内消费过的客户
            $c = array_intersect($a,$b);
            // 获取时间端内没有消费过的客户
            $d = array_diff($a,$c);
            $addNumAll = [];
            foreach ($d as $key => $val){
                $thisOne = [];
                $thisOne['customer_id'] = $val;
                $thisOne['num']         = $bei;
                array_push($addNumAll,$thisOne);
            }
            Db::name('customer_num')->insertAll($addNumAll);
            $All = $All + count($addNumAll);
        }
        return resultArray(['error' => '处理成功'.$All, 'data'=>[]]);
     }
     public function setmonth()
     {
        $list = Db::name('customer_num')->limit('3000')->select()->toArray();
        $num = count($list);

        if($num > 0){
            $num1 = $num -1;
            foreach ($list as $key => $val){
                $save = [];
                $save['month'.$val['num']] = $val['num'];
                // print_r($save);
                // print_r($val);
                // exit;
                Db::name('customer')->where('id','=',$val['customer_id'])->update($save);
                Db::name('customer_num')->where('id','=',$val['id'])->delete();
            }
        }
        return resultArray(['error' => '处理成功'.$num, 'data'=>[]]);
     }
     /**
      * 小程序用户列表
      */
     public function wxList(): json
     {
         $request = request()->param();

        //  try {
            $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
            $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
            $where      = [];
            $telephone = $request['phone'] ?? '';
            $customer_name = $request['name'] ?? '';
            if ($telephone) {
                array_push($where,['telephone','=',$telephone]);
            }
            if ($customer_name) {
                // $customerList  = Db::name('customer')->where('customer_name', 'like', '%'.$categoryIdArr.'%')->column('id');
                array_push($where,['nickName','like',$customer_name]);
            }
            // $categoryId && array_push($where, ['category_id', '=', $categoryId]);
            $dataCount = Db::name('mini_program_fans')->where($where)->count();
            if ($dataCount) {
                $field = ['id', 'nickName', 'telephone', 'gender','customerId'];
                $list  = Db::name('mini_program_fans')->where($where)->field($field)->order('id DESC')
                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                    ->select()->toArray();
                $categoryIdArr = array_unique(array_column($list, 'customerId'));
                $categoryList  = Db::name('customer')->where('id', 'in', $categoryIdArr)->column('shop_id', 'id');
                $shopIdArr = array_unique(array_column($list, 'shop_id'));
                $shopList  = Db::name('shop')->where('shop_id', 'in', $shopIdArr)->column('shop_name', 'shop_id');
                foreach ($list as $key => $val) {
                    // $list[$key]['category_name'] = $shopList[$categoryList[$val['id']]] ?? '';
                    // $list[$key]['shop_name'] = isset($shopList[$categoryList[$val['customerId']]]['shop_name']) ? $shopList[$categoryList[$val['customerId']]]['shop_name'] : '';
                    $list[$key]['shop_name'] = '';
                }
            }

            $data              = [];
            $data['list']      = $list ?? [];
            $data['dataCount'] = $dataCount ?? 0;
        // } catch (\Exception $e) {
        //      return resultArray(['data' => []]);
        //  }

        // $this->error = '暂无此数据';
        // return [];
        return resultArray(['data' => $data]);
     }

    /**
      * 小程序用户列表
      */
     public function wxList_export()
     {
         $request = request()->param();
         $id = $request['id'] ?? [];
         try {
            $where      = [];
            $telephone = $request['telephone'] ?? '';
            $customer_name = $request['customer_name'] ?? '';
            if ($telephone) {
                array_push($where,['telephone','=',$telephone]);
            }
            if ($customer_name) {
                // $customerList  = Db::name('customer')->where('customer_name', 'like', '%'.$categoryIdArr.'%')->column('id');
                array_push($where,['nickName','like',$customer_name]);
            }
            // $categoryId && array_push($where, ['category_id', '=', $categoryId]);
            array_push($where,['id','in',$id]);
            $dataCount = Db::name('mini_program_fans')->where($where)->count();
            if ($dataCount) {
                $field = ['id', 'nickName', 'telephone', 'gender','customerId'];
                $list  = Db::name('mini_program_fans')->where($where)->field($field)->order('id DESC')
                    ->select()->toArray();
                $categoryIdArr = array_unique(array_column($list, 'customerId'));
                $categoryList  = Db::name('customer')->where('id', 'in', $categoryIdArr)->column('shop_id', 'id');
                $shopIdArr = array_unique(array_column($list, 'shop_id'));
                $shopList  = Db::name('shop')->where('shop_id', 'in', $shopIdArr)->column('shop_name', 'shop_id');
                foreach ($list as $key => $val) {
                    // $list[$key]['category_name'] = $shopList[$categoryList[$val['id']]] ?? '';
                    $list[$key]['shop_name'] = '';
                    $list[$key]['is_shop']   = '';
                }
            }

            if(empty($list)){
                $data['list'] = [];
            }
            $callName = ['nickName' => '客户姓名','telephone' =>'手机号','consignee' =>'性别','gender' => '年龄','is_shop' => '是否进店','shop_name' => '归属门店'];
            // print_r($callName);exit;
            $downUrl = exportExcelData('wxlist',$callName,$list,'xlsx',1);
            return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
        } catch (\Exception $e) {
             return resultArray(['data' => []]);
         }

        // $this->error = '暂无此数据';
        // return [];
        return resultArray(['data' => $data]);
     }

     /**
      * 获取当前登录用户可以读取的店铺列表
      * 未完成
      */
    public function getCustomerShopList(CustomerModel $customerModel): Json
    {
        $param = $this->param;
        $type  = isset($param['type']) ? intval($param['type']) : 0;

        /*调用读取shop_id集合的方法*/
        $where = array();
        if ($param['type'] == 0){
            $data           = Db::name('shop')->where($where)->column('shop_id,shop_name');
        }else{
            $data['out']    = Db::name('shop')->where($where)->column('shop_id,shop_name');
            $data['enter']  = Db::name('shop')->where($where)->column('shop_id,shop_name');
        }

        return resultArray(['data' => $data]);
    }

    /**
     * 列表
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function list(CustomerModel $customerModel): Json
    {

        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['shop_person_id'] = $this->userInfo['shop_person_id'];

        $data = $customerModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }

        if(!empty($this->param['export']) && $this->param['export'] == 1)
        {
            $callName = [
                'create_time'      => '录入时间',
                'customer_name'      => '姓名',
                'telephone'      => '联系电话',
                'sex'      => '性别',
                'age'      => '年龄',
                'birthday'      => '生日',
                'source_name'      => '来源',
                'type_store_name'      => '到店类型',
                'is_transfer'      => '是否中台转店',
                'turn_status'      => '转店状态',
                'doctor_name'      => '主治医师',
                'nurse_name'      => '责任护士',
                'developers_name'      => '咨询师',
                'operator_name'      => '创建人',
                'shop_name'      => '门诊',
                'king_no'      => 'K3码',
                'repair_progress_name'      => '治疗进展',
                'department'      => '治疗科室',
                'item_names_str'      => '咨询项目',
                'consumption'      => '消费金额',
            ];

            $downUrl = exportExcelData('客户列表',$callName,$data['data'],'xlsx',1);
            return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
        }else
        {
            return resultArray(['data' => $data]);
        }
    }

    /**
     * 新单列表
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function newOrderlist(CustomerModel $customerModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id']    = $this->userInfo['id'];
        $this->param['shopIds']    = $shopIds;
		$this->param['isNewOrder']    = 1;
        $data = $customerModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

	/**
	 * 回访列表
	 * @param  CustomerModel $customerModel
	 * @return Json
	 */
	public function clientVisitlist(CustomerModel $customerModel): Json
	{
	    $shopIds = $this->getCommonShopIdsCollectByUserType();
	    $this->param['user_id']    = $this->userInfo['id'];
	    $this->param['shopIds']    = $shopIds;

	    $data = $customerModel->getDataList($this->param);
	    if (!$data) {
	        return resultArray(['error' => $customerModel->getError()]);
	    }
	    return resultArray(['data' => $data]);
	}

    /**
     * 流失列表
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function drainlist(CustomerModel $customerModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['shopIds'] = $shopIds;
        $this->param['isDrain'] = 1;
        $data = $customerModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 预警列表
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function warninglist(CustomerModel $customerModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['shopIds'] = $shopIds;
        $this->param['isWarning'] = 1;
        $data = $customerModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 审核列表
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function auditList(Service $serviceModel): Json
    {
        // $data = [
        //     'list' => '审核列表'
        // ];
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['shopIds'] = $shopIds;
        // $this->param['isWarning'] = 1;
        $data = $serviceModel->auditList($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 提交审核
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function submitAudit(Service $serviceModel)
    {

        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['shopIds'] = $shopIds;
        // $this->param['isWarning'] = 1;
        $data = $serviceModel->submitAudit($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 商机详情
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function read(CustomerModel $customerModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['user_phone'] = $this->userInfo['mobile'];

        $data = $customerModel->getDataInfo($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 获取客户门诊id
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function readCustomerId(CustomerModel $customerModel): Json
    {
        $request = $this->param;

        $telephone = Db::name('customer')->where('id',$request['id'])->value('telephone');

        $ids = Db::name('customer')->alias('c')
        ->join('shop s', 's.shop_id = c.shop_id', 'LEFT')
        ->where('c.telephone',$telephone)->column('c.id','s.shop_type');


        return resultArray(['data' => $ids]);
    }

    /**
     * 添加
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function create(CustomerModel $customerModel): Json
    {
        $this->param['operator'] = $this->userInfo['id'];
        $data = $customerModel->addData($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['error' => $customerModel->getError(), 'data'=>[]]);
    }

    /**
     * 编辑
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function update(CustomerModel $customerModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $customerModel->saveData($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['error' => $customerModel->getError(), 'data'=>[]]);
    }

    /**
     * 基础设置列表
     * @param  SettingCategory $settingCategory
     * @return Json
     */
    public function settingCategory(SettingCategory $settingCategory): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingCategory->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $settingCategory->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 基础设置列表
     * @param  SettingCategory $settingCategory
     * @return Json
     */
    public function settingInfo(Setting $setting): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $setting->settingInfo($this->param);
        if (!$data) {
            return resultArray(['error' => $setting->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 基础设置列表
     * @param  Setting $settingModel
     * @return Json
     */
    public function settingList(Setting $settingModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingModel->getAllDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $settingModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 基础设置列表
     * @param  Setting $settingModel
     * @return Json
     */
    public function setting(Setting $settingModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $settingModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 添加
     * @param  Setting $settingModel
     * @return Json
     */
    public function createSetting(Setting $settingModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingModel->addData($this->param);
        if (!$data) {
            return resultArray(['error' => $settingModel->getError()]);
        }
        return resultArray(['error' => $settingModel->getError(), 'data'=>[]]);
    }

    /**
     * 编辑
     * @param  Setting $settingModel
     * @return Json
     */
    public function updateSetting(Setting $settingModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingModel->saveData($this->param);
        if (!$data) {
            return resultArray(['error' => $settingModel->getError()]);
        }
        return resultArray(['error' => $settingModel->getError(), 'data'=>[]]);
    }

    /**
     * 删除
     * @param  Setting $settingModel
     * @return Json
     */
    public function deleteSetting(Setting $settingModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingModel->deleteData($this->param);
        if (!$data) {
            return resultArray(['error' => $settingModel->getError()]);
        }
        return resultArray(['error' => $settingModel->getError(), 'data'=>[]]);
    }

    /**
     * 状态
     * @param  Setting $settingModel
     * @return Json
     */
    public function statusSetting(Setting $settingModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingModel->statusData($this->param);
        if (!$data) {
            return resultArray(['error' => $settingModel->getError()]);
        }
        return resultArray(['error' => $settingModel->getError(), 'data'=>[]]);
    }

    /**
     * 转店列表
     * @param  TransferShop $transferShop
     * @return Json
     */
    public function transferShopList(TransferShop $transferShop): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $transferShop->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $transferShop->getError()]);
        }
        return resultArray(['data' => $data]);
    }

        /**
     * 转店列表 导出
     * @param  TransferShop $transferShop
     * @return Json
     */
    public function transferShopList_export(TransferShop $transferShop): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['export']  = 1;
        $data = $transferShop->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $transferShop->getError()]);
        }
        $callName = [
            'out_shop_name' => '转出门店/门诊',
            'create_time' =>'转出时间',
            'customer_name' =>'客户名称',
            'operator_name' => '操作员工',
            'in_shop_name' => '转入门店/门诊',
            'reason' => '转店原因'
            ];
        $downUrl = exportExcelData('list',$callName,$data['list'],'xlsx',1);
        return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
    }

    /**
     * 手机号验证
     * @param  TransferShop $transferShop
     * @return Json
     */
    public function verifyPhone(TransferShop $transferShop): Json
    {

        $data = $transferShop->verifyPhone($this->param);
        if (!$data) {
            return resultArray(['error' => $transferShop->getError()]);
        }
        return resultArray(['data' => $data]);
    }


    /**
     * 添加转店
     * @param  TransferShop $transferShop
     * @return Json
     */
    public function transferShop(TransferShop $transferShop): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $transferShop->addData($this->param);
        if (!$data) {
            return resultArray(['error' => $transferShop->getError()]);
        }
        return resultArray(['error' => $transferShop->getError(), 'data'=>[]]);
    }

    /**
     * 服务列表
     * @param  Service $serviceModel
     * @return Json
     */
    public function serviceList(Service $serviceModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['user_shop_id'] = $this->userInfo['shop_id'];

        $this->param['shop_person_id'] = $this->userInfo['shop_person_id'];

        $data = $serviceModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }

        // 导出
        $is_export = $this->param['export'] ?? 0;

        if($is_export == 1){

            $callName = [

                'create_time'   =>'开卡日期',

                'customer_name' =>'顾客姓名',
                'telephone' =>'手机号',

                'source_name' =>'来源',

                'last_shop_time'=>'最新到店日期',

                'kk_user_name' =>'开卡人',

                'shop_name' =>'开卡部门',

                'name' =>'开卡名称',
                'goods_alias_name' =>'开卡别名',

                'kk_money'     =>'开卡金额',
                'consume_money'=>'消耗本金',
                'consume_gratuity'=>'消耗赠金',
                'consume_store_transfer'=>'消耗店转',

                'num'   =>'开卡次数',

                'yy_num'    =>'剩余次数',

                'start_time'    =>'开始时间',

                'end_time'      =>'结束时间',

                'sy_num'    =>'消耗次数',
                'remark'  =>'备注'
            ];


            if($data['list']){


                $downUrl = exportExcelData('服务列表导出',$callName,$data['list'],'xlsx',1);

                return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

                exit;

            }else{

                return resultArray(['error' => '请选择导出门店！！！']);

            }


        }

        return resultArray(['data' => $data]);
    }

    /**

	 * 核销列表

	 * @param  Service $serviceModel

	 * @return Json

	 */
	public function serveContent(Service $serviceModel): Json
	{

		$shopIds = $this->getCommonShopIdsCollectByUserType();
		$this->param['shopIds'] = $shopIds;
		$this->param['user_id'] = $this->userInfo['id'];
        $this->param['shop_person_id'] = $this->userInfo['shop_person_id'];
		$data = $serviceModel->getDataLog($this->param);
		if (!$data) {
		    return resultArray(['error' => $serviceModel->getError().'23232']);
		}
        $is_export = $this->param['export'] ?? 0;
        if($is_export == 1)
        {
            if(date('Y-m',strtotime($this->param['start_time'])) != date('Y-m',strtotime($this->param['endTime'])))
                return resultArray(['error' => "只能导出一个月内的数据"]);

            $callName = [

                'create_time'   =>'服务日期',
                'kk_time' =>'开卡日期',
                'customer_name' =>'客户姓名',
                'sex' =>'性别',
                'age' =>'年龄',
                'shop_name' =>'门店',
                'market_name'     =>'市场',
                'nurse_name'   =>'负责人',
                'name'    =>'卡项名称',
                'consume_money'=>'消耗本金',
                'consume_gratuity'=>'消耗赠金',
                'nurse_id_one_name'    =>'护理师1',
                'nurse_id_two_name'      =>'护理师2',
                'experience'    =>'服务类型',
                'fw_num'    =>'服务次数',
                'station_name'    =>'核销店长',
                'pt'    =>'核销平台',
                'mark'  =>'备注'
            ];

            if($data['service_log']){
                $downUrl = exportExcelData('核销列表导出',$callName,$data['service_log'],'xlsx',1);
                return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
                exit;
            }else{
                return resultArray(['error' => '请选择导出门店！！！']);
            }
        }
		return resultArray(['data' => $data]);
	}


	/**

	 * 核销列表 - 查看照片

	 * @param  Service $serviceModel

	 * @return Json

	 */
	public function serveContentImage(Service $serviceModel): Json
	{

		$shopIds = $this->getCommonShopIdsCollectByUserType();
		$this->param['shopIds'] = $shopIds;
		$this->param['user_id'] = $this->userInfo['id'];
        $this->param['shop_person_id'] = $this->userInfo['shop_person_id'];
		$data = $serviceModel->getDataLogImage($this->param);
		return resultArray(['data' => $data]);
	}



	/**

	 * 护理统计

	 * @param  Service $serviceModel

	 * @return Json

	 */
	public function serviceNursing(Service $serviceModel): Json
	{
		$shopIds = $this->getCommonShopIdsCollectByUserType();

		$this->param['shopIds'] = $shopIds;

		$this->param['user_id'] = $this->userInfo['id'];

		$data = $serviceModel->getDataNursing($this->param);
//        $totalData = $serviceModel->getTotalData($this->param);
        // echo "<pre>";
        // print_r($data['service_log']);
        // exit;
		//print_r($data);
		if (!$data) {

		    return resultArray(['error' => $serviceModel->getError()]);

		}
//        array_push($data['service_log'],$totalData);

        $is_export = $this->param['export'] ?? 0;

        if($is_export == 1){

            $callName = [

                'market_name'   =>'市场',

                'shop_name' =>'门店',

                'name' =>'员工姓名',

                'station_name' =>'等级',

                'bahennum' =>'疤痘护理',

                'mianbunum'     =>'面部护理',

                'shentinum'   =>'项目身体护理',

                'shengming'    =>'生命之源',

                'jingluotong'    =>'经络通',

                'shuganliqi'      =>'疏肝理气',

                'jichubushui'    =>'基础补水',

                'total'    =>'护理总数',

            ];


            if($data['service_log']){


                $downUrl = exportExcelData('护理统计明细',$callName,$data['service_log'],'xlsx',1);

                return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

                exit;

            }else{

                return resultArray(['error' => '请选择导出门店！！！']);

            }


        }


		return resultArray(['data' => $data]);


	}

    /**
     * 服务详情
     * @param  Service $serviceModel
     * @return Json
     */
    public function readService(Service $serviceModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $serviceModel->getDataInfo($this->param);
        if (!$data) {
            return resultArray(['data' => $data,'error' => $serviceModel->getError()]);
        }
        return resultArray(['data' => $data,$serviceModel->getError()]);
    }

    /**
     * 服务详情
     * @param  Service $serviceModel
     * @return Json
     */
    public function addServiceLog(Service $serviceModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $serviceModel->addServiceLog($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }
        return resultArray(['data' => $data,'error' => $serviceModel->getError()]);
    }


     /**
     * 调整服务卡项
     * @param  Service $serviceModel
     * @return Json
     */
    public function changeService(Service $serviceModel)
    {
        $this->param['user_id'] = $this->userInfo['id'];
        // echo "<pre>";
        // print_r($this->param);
        $data = $serviceModel->changeService($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }
        return resultArray(['data' => $data,'error' => $serviceModel->getError()]);
    }


    /**
     * 余额变动记录
     * @param  BalanceLog $balanceLog
     * @return Json
     */
    public function createBalanceLog(BalanceLog $balanceLog): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $balanceLog->addData($this->param);
        if (!$data) {

            return resultArray(['error' => $balanceLog->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 每年重新搞一下名字
     */
    public function setCustomerAge(CustomerModel $customerModel):Json
    {
        $data = $customerModel->setCustomerAge($this->param);
        if (!$data) {

            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['data' => []]);
    }

    /**
     * 更新进店时间
     * 更新转店状态
     */
    public function setCustomerStatus(CustomerModel $customerModel):Json
    {
        $param  = $this->param;
        $data = $customerModel->setCustomerStatus($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['error' => '更新成功','data' => []]);
    }

    /**
     * 会员等级列表
     */
    public function getGradeList(CustomerGradeModel $CustomerGradeModel): Json
    {
        $param  = $this->param;
        $data   = $CustomerGradeModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerGradeModel->getError()]);
        }
        return resultArray(['error' => '','data' => $data]);
    }

    /**
     * 添加会员等级的基础数据获取
     */
    public function addGradeDetail(CustomerGradeModel $CustomerGradeModel): Json
    {
        $param = $this->param;
        $data   = $CustomerGradeModel->addGradeDetail($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerGradeModel->getError()]);
        }
        return resultArray(['error' => '','data' => $data]);
    }

    /**
     * 添加会员等级
     */
    public function addGrade(CustomerGradeModel $CustomerGradeModel): Json
    {
        $param = $this->param;
        $data   = $CustomerGradeModel->addGrade($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerGradeModel->getError()]);
        }
        return resultArray(['error' => '添加成功','data' => $data]);
    }

    /**
     * 编辑会员等级
     */
    public function saveGrade(CustomerGradeModel $CustomerGradeModel): Json
    {
        $param = $this->param;
        $data   = $CustomerGradeModel->saveGrade($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerGradeModel->getError()]);
        }
        return resultArray(['error' => '编辑成功','data' => $data]);
    }

    /**
     * 获取详情
     */
    public function gradeDetail(CustomerGradeModel $CustomerGradeModel): Json
    {
        $param = $this->param;
        $data   = $CustomerGradeModel->gradeDetail($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerGradeModel->getError()]);
        }
        return resultArray(['error' => '','data' => $data]);
    }

    /**
     * 某个客户的优惠券
     */
    public function getCouponProvide(): Json
    {
        $param      = $this->param;
        $shop_id    = $param['shop_id'] ?? 0;
        $customer_id= $param['customer_id'] ?? 0;
        $type= $param['type'] ?? 0;

        if ($shop_id == 0 && $customer_id == 0 ) {
            return resultArray(['error' => '数据类型错误']);
        }

        $where = array();
        if ($shop_id) {

        } else {
            array_push($where,['customer_id','=',$customer_id]);

            $c_where = [];

            array_push($c_where,['start_time','<',time()]);
            array_push($c_where,['end_time','>',time()]);
            $shop_goods = Db::name('coupon')->where($c_where)->column('id');

            array_push($where,['coupon_id','in',$shop_goods]);
        }
        $list       = Db::name('coupon_provide_customer')->where($where)->select()->toArray();
        $yhjIds     = array_column($list,'coupon_id');
        if ($yhjIds) {
            $files = [
                'id',
                'name',
                'use_type',
                'type',
                'use_threshold',
                'denomination',
                'start_time',
                'end_time',
                'status',
            ];
            $where = [];
            array_push($where,['id','in',$yhjIds]);
            if($type == 1){
                array_push($where,['type','=',$type]);
            }else if($type == 2){
                array_push($where,['type','=',$type]);
            }else if($type == 3){
                array_push($where,['type','=',$type]);
            }
            $yhjlist   = Db::name('coupon')->where($where)->column($files,'id');
            // print_r($yhjlist);exit;
        }
        foreach ($list as $key => $val){
            if ($yhjlist[$val['coupon_id']]['end_time'] >= time() && $yhjlist[$val['coupon_id']]['start_time'] <= time() && $yhjlist[$val['coupon_id']]['status'] != 1 ) {
                $list[$key]['status']    = 2;
            }
            if ($yhjlist[$val['coupon_id']]['start_time'] > time()) {
                $list[$key]['status']    = 3;
            }
            // print_r($val);
            // print_r($yhjlist);
            // $list[$key]['id']            = $yhjlist[$val['id']]['id'] ? $yhjlist[$val['id']]['id'] : 0;
            $list[$key]['name']          = $yhjlist[$val['coupon_id']]['name'] ? $yhjlist[$val['coupon_id']]['name'] : '';
            $list[$key]['use_type']      = $yhjlist[$val['coupon_id']]['use_type'] ? $yhjlist[$val['coupon_id']]['use_type'] : 0;
            $list[$key]['use_threshold'] = $yhjlist[$val['coupon_id']]['use_threshold'] ? $yhjlist[$val['coupon_id']]['use_threshold'] : 0;
            $list[$key]['denomination']  = $yhjlist[$val['coupon_id']]['denomination'] ? $yhjlist[$val['coupon_id']]['denomination'] : 0;
            $list[$key]['start_time']    = $yhjlist[$val['coupon_id']]['start_time'] ? date('Y-m-d H:i:s',$yhjlist[$val['coupon_id']]['start_time']) : 0;
            $list[$key]['end_time']      = $yhjlist[$val['coupon_id']]['end_time'] ? date('Y-m-d H:i:s',$yhjlist[$val['coupon_id']]['end_time']) : 0;
            // $list[$key]['status']        = $yhjlist[$val['id']]['id'] ? $yhjlist[$val['id']]['id'] : 0;
            $list[$key]['create_time']      = $list[$key]['create_time'] ? date('Y-m-d H:i:s',$list[$key]['create_time']) : 0;
            $list[$key]['use_time']      = $list[$key]['use_time'] ? date('Y-m-d H:i:s',$list[$key]['use_time']) : '未使用';
            $list[$key]['endTimeT']      = $yhjlist[$val['coupon_id']]['end_time'] ? $yhjlist[$val['coupon_id']]['end_time'] : 0;
			$type = $yhjlist[$val['coupon_id']]['type'] ?? 0;
            if ($type == 1) {
                // code...
                $type_name = '满减券';
            }else if($type == 2){
                $type_name = '满赠券';
            }else {
                $type_name = '兑换券';
            }
            $list[$key]['type_name']      = $type_name;
            $list[$key]['type']      = $type;
        }

		/* $i = 0;
		foreach ($list as $k => $v){

			if($v['endTimeT'] >= time()){

				$list_t[$i]['id'] =$v['id'];
				$list_t[$i]['coupon_id'] =$v['coupon_id'];
				$list_t[$i]['customer_id'] =$v['customer_id'];
				$list_t[$i]['staus'] =$v['staus'];
				$list_t[$i]['create_time'] =$v['create_time'];
				$list_t[$i]['use_time'] =$v['use_time'];
				$list_t[$i]['order_id'] =$v['order_id'];
				$list_t[$i]['order_sn'] =$v['order_sn'];
				$list_t[$i]['user_id'] =$v['user_id'];
				$list_t[$i]['name'] =$v['name'];
				$list_t[$i]['use_type'] =$v['use_type'];
				$list_t[$i]['use_threshold'] =$v['use_threshold'];
				$list_t[$i]['denomination'] =$v['denomination'];
				$list_t[$i]['start_time'] =$v['start_time'];
				$list_t[$i]['end_time'] =$v['end_time'];
				$list_t[$i]['type_name'] =$v['type_name'];
				$list_t[$i]['type'] =$v['type'];

				$i ++;
			}else{
				$list_t[0]['dd']=1;
			}

		} */
		/* echo '<pre>';
		print_r($list_t);exit; */
        return resultArray(['error' => '','data' => $list]);
    }
    /**
     * 某个客户的优惠券兑换时的客户信息
     */
    public function getCouponProvideCustomer(): Json
    {
        $param      = $this->param;
        $yhj_id     = $param['yhj_id'] ?? 0;

        $where = [];
        array_push($where,['id','=',$yhj_id]);
        $fubiaoInfo     = Db::name('coupon_provide_customer')->where($where)->find();
        if (empty($fubiaoInfo)) {
            return resultArray(['error' => '优惠券不存在']);
        }
        $yhjInfo        = Db::name('coupon')->where('id','=',$fubiaoInfo['coupon_id'])->find();
        if (empty($yhjInfo)) {
            return resultArray(['error' => '优惠券不存在']);
        }
        $customerInfo   = Db::name('customer')->where('id','=',$fubiaoInfo['customer_id'])->find();
        if (empty($customerInfo)) {
            return resultArray(['error' => '客户不存在']);
        }
        $shopInfo   = Db::name('shop')->where('shop_id','=',$customerInfo['shop_id'])->find();
        if (empty($shopInfo)) {
            return resultArray(['error' => '店铺不存在']);
        }
        $personInfo   = Db::name('shop_person')->where('id','=',$customerInfo['nurse_id'])->find();
        if (empty($personInfo)) {
            return resultArray(['error' => '护理师不存在']);
        }
        $data = [];
        // 销售部门
        $data['sales_name']       = $shopInfo['shop_name']; //店名
        // 客户姓名
        $data['customer_name']    = $customerInfo['customer_name']; // 客户名称
        // 护理师（开单人）
        $data['sale_name']        = $personInfo['name']; // 护理师
        // 业务类型
        $data['business_type']    = $yhjInfo['use_type'] == 1 ? '疤痕' :'项目'; // 优惠券的类型
        // 订单类型
        $data['order_type']       = '补单'; // 默认补单
        // 销售组织
        $data['sales_organization']       = $shopInfo['market_name']; // 门店的归属市场
        // 发货组织
        $data['settlement_name']  = $shopInfo['market_name']; // 门店的归属市场
        // 发货部门
        $data['settlement_bumen_name']    = $shopInfo['market_name']; // 门店的归属市场
        // 发货仓库
        $data['settlement_cangku_name']  = $shopInfo['store_name'];  // 门店的归属市场
        // 成交日期
        $data['deal_time']        = date('Y-m-d'); // 当前时间
        $data['goodsList']        = []; // 可兑换的商品集合

        $goodsIds    = $yhjInfo['goods_id'];
        if ($goodsIds) {
            // code...
            $goodsList  = Db::name('shop_goods')->where('id','in',$goodsIds)->select()->toArray();
            foreach ($goodsList as $key => $val){
                $goodsList[$key]['pay_price'] = '0.00';
                $goodsList[$key]['number'] = '1';
            }
            $data['goodsList'] = $goodsList;
        }
        return resultArray(['error' => '获取成功','data' => $data]);
    }
   /**
     * 获取订单支付金额
     */
    public function getPayment(): Json
    {

        try {
            $param = $this->param;
            // 设置返回数据
            $balanceType = [
                1=>[
                    'this' => 'zc_goods',
                    'all'  => 'zc_allgoods'
                ],
                2=>[
                    'this' => 'zc_fuwu',
                    'all'  => 'zc_allfuwu'
                ],
                3=>[
                    'this' => 'zc_fuwu',
                    'all'  => 'zc_allfuwu'
                ],
                4=>[
                    'this' => 'zc_fuwu',
                    'all'  => 'zc_allfuwu'
                ],
            ];
            $retuenData = [
                'zc_goods_y'    => '0.00', // 疤痕需要支付的余额
                'zc_goods_z'    => '0.00', // 疤痕需要支付的赠金
                'zc_allgoods_z' => '0.00', // 疤痕需要支付的总金额
                'zc_fuwu_y'     => '0.00', // 服务需要支付的余额
                'zc_fuwu_z'     => '0.00', // 服务需要支付的赠金
                'zc_allfuwu_z'  => '0.00',
                'yhj_list'      => [],
            ];

            //获取订单总金额
            $order_amout       = isset($param['order_amout']) ? $param['order_amout'] : 0;         // 订单总计
            $customer_id       = isset($param['customer_id']) ? intval($param['customer_id']) : 0; // 客户id
            $yhj_amount        = isset($param['yhj_amount']) ? abs($param['yhj_amount']) : 0;      // 优惠劵金额
            $coupon_id       = isset($param['coupon_id']) ? $param['coupon_id'] : 0; // 优惠券id
            $order_goods       = isset($param['goods']) ? $param['goods'] : []; // 订单商品

            if ($order_amout < 0) {
                // 如果订单金额为0，则直接返回数据
                throw new \Exception('订单金额异常，无法获取客户支付金额');
            }
            if(empty($order_goods)){
                throw new \Exception('无需出库商品');
            }
            $balance = CustomerAccount::where('id',$customer_id)->find();
            if(empty($balance)){
                throw new \Exception('客户余额数据异常');
            }
            $benj = $balance['balance'];
            $zengj = $balance['gift'];

            $customerMoney = bcadd($benj,$zengj,2);
            if($customerMoney<0){
                throw new \Exception('客户余额为负,无法下单');
            }


            $prestock_goods_ids = [];
            $customerModel = new CustomerModel();
            $kcbj = $kczj =  $kcdz = [];
            $yhq_yh_bj = $yhq_yh_zj = $yhq_yh_dz = [];
            $cjyh_yh_bj = $cjyh_yh_zj = $cjyh_yh_dz = [];
            $product_arr = $project_arr = $product_project_arr = [];
            $productAmount = [];
            $projectAmount = [];
            $is_have_cjyh = [];
            $is_have_goods = [];
            $is_have_service = [];
            $cjyh = 0;

            foreach($order_goods as $k=>$val){
                if($val['prestock_type'] != 3){

                    if($val['prestock_type'] == 2){
                        array_push($prestock_goods_ids,$val['id']);
                    }
                    if($val['goods_type'] == 2 && $val['prestock_type'] != 3){
                        if($val['id'] != 170 && $val['pay_price'] != 0){
                            if($val['pay_price'] <0){
                                throw new \Exception($val['name'].'-售卖价格错误');
                            }
                            array_push($product_project_arr,$val);
                            $productAmount[] = bcmul($val['pay_price'], $val['number'], 2);
                        }
                        array_push($is_have_goods,1);

                    }elseif($val['goods_type'] ==1 && $val['prestock_type'] != 3  && $val['pay_price'] != 0 ){
                        $projectAmount[] = bcmul($val['pay_price'], $val['number'], 2);
                        array_push($is_have_goods,1);
                        array_push($product_project_arr,$val);
                    }

                    if($val['id'] == 170 ){
                        $cjyh = bcmul($val['pay_price'], $val['number'], 2);
                        array_push($is_have_cjyh,1);
                    }
                }
            }

            if(!empty($prestock_goods_ids)){
                //排查如果有预存货不能添加-针对预存货商品，进行判定
                $may_prestock_ids = ShopGoods::where('is_prestock',1)->column('id'); //可以预存货的id
                $prestock_diff = array_diff($prestock_goods_ids,$may_prestock_ids);
                if(!empty($prestock_diff)){
                    throw new \Exception('有异常预存货商品');
                }
            }

            $is_have_cjyh_count = count($is_have_cjyh);
            if($is_have_cjyh_count >1){
                throw new \Exception('同一个单子不能出现两项冲减优惠');
            }

            if($is_have_cjyh_count >0 && empty($is_have_goods)){
                throw new \Exception('冲减优惠没有优惠商品');
            }


            $productAmount = bcadd(0,array_sum($productAmount),2); //商品之和
            $projectAmount = bcadd(0,array_sum($projectAmount),2); //项目之和

            $productProjectAmount = bcadd($productAmount,$projectAmount,2);

            if($is_have_cjyh_count >0 && $productProjectAmount<$cjyh){
                throw new \Exception('冲减优惠无法使用');
            }

            // 获取实际支付的订单金额数据和对应客户需要支付的金额数据
            $actual_order_amout  = bcsub($order_amout,$yhj_amount,2); // 获取订单的实际需要支付金额
            if ($actual_order_amout <= 0) {
                return resultArray(['data' => $retuenData,'error'=>'获取成功']);
            }
            // 如果订单金额为0，则直接返回数据
            if ($order_amout == 0) {
                return resultArray(['data' => $retuenData,'error'=>'获取成功']);
            }

            $product_project_arr_count = count($product_project_arr);
            $product_arr_count = count($product_arr);
            $project_arr_count = count($project_arr);

            $yhq_amount  = $yhj_amount;

            $orderModel = new Order();

            $product_yh_amount =  $product_one_amount = [];
            $discount_amount_arr = [];//冲减优惠-商品优惠后的总金额
            foreach($product_project_arr as $pk=>&$pv){
                if($pv['pay_price'] >0 && $pv['prestock_type'] != 3){

                    $customerBalance['money'] = $benj;
                    $customerBalance['complimentary_money'] = $zengj;

                    $one_product_amount = bcmul($pv['pay_price'],$pv['number'],2);
                    $discount_amount = 0; //优惠金额
                    if($productProjectAmount >0 && $cjyh != 0 ){
                        //涉及到冲减优惠
                        if($product_project_arr_count > 1 ){
                            if($pk+1 == $product_project_arr_count){
                                $discount_amount = bcsub($cjyh,bcadd(0,array_sum($discount_amount_arr),2),2); //最后一个优惠金额
                            }else{
                                $discount_amount = bcmul($cjyh,($one_product_amount/$productProjectAmount),2); //优惠金额
                            }
                        }else{
                            $discount_amount = bcmul($cjyh,($one_product_amount/$productProjectAmount),2); //优惠金额
                        }

                        $one_product_amount = bcadd($one_product_amount,$discount_amount,2);
                    }
                    array_push($discount_amount_arr,$discount_amount);

                    $customerBalance['actual_order_amout'] = $one_product_amount;
                    $pay_money = $customerModel->getCustomerAmountConsumed($customerBalance); //获取订单消耗的本金、赠金、店转
                    $bj = bcadd($pay_money['pay_benjin_amount'],0,2);  //单条优惠后的本金
                    $zj = bcadd($pay_money['pay_zengjin_amount'],0,2); //单条优惠后的赠金
//                    var_dump('优惠金额：'.$discount_amount);
//                    var_dump('扣款本金：'.$bj.'扣款赠金'.$zj);

                    array_push($kcbj ,$bj);
                    array_push( $kczj ,$zj);

                    $pv['product_amount'] = $one_product_amount;    //优惠后金额
                    array_push($product_yh_amount,$discount_amount);
                    array_push($product_one_amount,$one_product_amount);
                }
            }

            $business_type = 2;
            $retuenData[$balanceType[$business_type]['this'].'_y'] = bcadd(array_sum($kcbj),0,2); //实际支付本金
            $retuenData[$balanceType[$business_type]['this'].'_z'] = bcadd(array_sum($kczj),0,2);  //实际支付

            // 设置支付总金额
            $retuenData[$balanceType[$business_type]['all'].'_z']  = $actual_order_amout;
            $yhjlist     = CouponProvideCustomer::where('customer_id',$customer_id)->where('staus',0)->select()->toArray();
            $yhjzbIds    = array_unique(array_column($yhjlist,'coupon_id'));
            $yhjZbList   = Coupon::whereIn('id',$yhjzbIds)->column(['use_type','type','denomination','use_threshold','name','start_time','end_time'],'id');

            $allList = [];
            foreach ($yhjlist as $key => $val){
                if (isset($yhjZbList[$val['coupon_id']])) {
                    //时间满足
                    if ($yhjZbList[$val['coupon_id']]['start_time'] <= time() && time() <= $yhjZbList[$val['coupon_id']]['end_time']) {
                        //金额满足
                        if ($yhjZbList[$val['coupon_id']]['use_threshold'] == 0 || $order_amout >= $yhjZbList[$val['coupon_id']]['use_threshold']){
                            $yhjlist[$key]['use_type']      = $yhjZbList[$val['coupon_id']]['use_type'];
                            $yhjlist[$key]['type']          = $yhjZbList[$val['coupon_id']]['type'];
                            $yhjlist[$key]['denomination']  = $yhjZbList[$val['coupon_id']]['denomination'];
                            $yhjlist[$key]['name']          = $yhjZbList[$val['coupon_id']]['name'];
                            $yhjlist[$key]['start_time']    = date('Y-m-d H:i:s',$yhjZbList[$val['coupon_id']]['start_time']);
                            $yhjlist[$key]['end_time']      = date('Y-m-d H:i:s',$yhjZbList[$val['coupon_id']]['end_time']);
                            array_push($allList,$yhjlist[$key]);
                        }
                    }
                }
            }
            $retuenData['yhj_list']  = $allList;
            return resultArray(['data' => $retuenData,'error'=>'获取成功']);
        }catch (\Exception $e){
            return resultArray(['error'=>$e->getMessage()]);
        }
    }







     /**
     * 服务列表
     * @param  Service $serviceModel
     * @return Json
     */
    public function readServiceList(Service $serviceModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $serviceModel->readServiceList($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

     /**
     * 服务列表导出
     * @param  Service $serviceModel
     * @return Json
     */
    public function readServiceList_export(Service $serviceModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['export'] = 1;
        $data = $serviceModel->readServiceList($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }
        $callName = ['create_time' => '服务日期','customer_name' =>'客户姓名','sex_name' =>'性别','age' => '年龄','shop_name' => '门店','market_name' => '市场','shop_name' => '服务人员','service_type_name' => '服务类型','sy_num' => '服务次数'];
            // print_r($callName);exit;
        $downUrl = exportExcelData('service',$callName,$data['list'],'xlsx',1);
        return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
    }

    /**
     * 新增客服回访
     */
    public function returnVistList(ReturnVist $ReturnVist): json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVist->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVist->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 新增客服回访
     */
    public function returnVistList_export(ReturnVist $ReturnVist): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['export']  = 1;
        $data = $ReturnVist->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVist->getError()]);
        }
        $callName = [
            'customer_name' => '客户名称',
            'telephone' =>'门店名称',
            'type' =>'回访类型',
            'return_visitor_name' =>'员工名称',
            'return_visit_time' => '客访时间',
            'return_visit_content' => '客访内容',
            'create_time' => '创建时间'
            ];
            // print_r($callName);exit;
        $downUrl = exportExcelData('list',$callName,$data['list'],'xlsx',1);
        return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
    }

    /**
     * 新增客服回访
     */
    public function addVistList(ReturnVist $ReturnVist): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVist->addData($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVist->getError()]);
        }
        return resultArray(['data' => $data,'error'=>'创建成功']);
    }


    /**
     * 咨询记录
     */
     public function returnConsult(ReturnConsult $ReturnConsult): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnConsult->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnConsult->getError()]);
        }
        if($this->param['export'] == 1)
        {
            $callName = [
                'customer_name' => '客户名称',
                'telephone' =>'手机号',
                'shop_name' =>'门店名称',
                'consult_name' =>'员工名称',
                'latent_demand'=>'潜在需求',
                'consult_time' => '咨询时间',
                'consult_content' => '咨询内容',
                'create_time' => '创建时间'
                ];
                // print_r($callName);exit;
            $downUrl = exportExcelData('咨询记录',$callName,$data,'xlsx',1);
            return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
        }else
        {
            return resultArray(['data' => $data]);
        }
    }

    /**
     * 新增咨询
     */
    public function addConsult(ReturnConsult $ReturnConsult): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnConsult->addData($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnConsult->getError()]);
        }
        return resultArray(['data' => $data,'error'=>'成功']);
    }


    /**
     * 获取修复进展
     */
    public function repairPlanList(ReturnVist $ReturnVist): json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVist->getRepairPlanList($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVist->getError()]);
        }
        return resultArray(['data' => $data]);
    }


    /**
     * 新增修复方案
     */
    public function addPlanList(ReturnVist $ReturnVist): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVist->addRepairData($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVist->getError()]);
        }
        return resultArray(['data' => $data,'error'=>'创建成功']);
    }

    /**
     * 回访列表
     */
    public function returnReturnVistT(ReturnVistT $ReturnVistT): json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVistT->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVistT->getError()]);
        }
        return resultArray(['data' => $data]);
    }
    /**
     * 回访列表
     */
    public function returnReturnVistT_export(ReturnVistT $ReturnVistT): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['list_type'] = 1;
        $this->param['export']  = 1;
        $data = $ReturnVistT->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVistT->getError()]);
        }

        $callName = [
            'return_visit_time' => '回访时间',
            'customer_name' =>'顾客姓名',
            'market_name' =>'归属市场',
            'shop_name' => '归属门店',
            'nurse_name' => '责任护理师',
            'result' => '回访结果',
            'result_name' => '问题分类',
            'total' => '综合评分',
            'early_warning' => '是否预警',
            'accountability' => '是否追责',
            ];
        // print_r($callName);exit;
        $downUrl = exportExcelData('list',$callName,$data['list'],'xlsx',1);
        return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
    }
    /**new
     * 创建回访
     */
    public function addReturnVistT(ReturnVistT $ReturnVistT): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVistT->addData($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVistT->getError()]);
        }
        return resultArray(['data' => [],'error' => '添加成功']);
    }

    /**
     * 更新回访
     */
    public function saveReturnVistT(ReturnVistT $ReturnVistT): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVistT->saveData($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVistT->getError()]);
        }
        return resultArray(['data' => $data,'error' => '添加成功']);
    }

    /***
     *添加跟进
     */
     public function addReturnVistTLog(ReturnVistT $ReturnVistT): json
     {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVistT->addReturnVistTLog($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVistT->getError()]);
        }
        return resultArray(['data' => $data,'error' => '添加成功']);
    }

    /***
     *获取回访详情
     */
     public function readReturnVistT(ReturnVistT $ReturnVistT): json
     {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVistT->readReturnVistT($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVistT->getError()]);
        }
        return resultArray(['data' => $data]);
    }

        /***
     * 获取优惠券的核销记录
     */
    public function getWriteOff(): json
    {
        $request = $this->param;
        // 获取需要的搜索参数 //
        $page  = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 15;
        $customer_name = $request['customer_name'] ?? 0;
        $shop_name     = $request['shop_name'] ?? 0;
        $market_id     = $request['market_id'] ?? 0;

        // 设置搜索条件 //
        $where = [];

        $userIds = [];
        if ($customer_name) {
            // array_push($where,['customer_id','=',$customer_id]);
            $userIds     = Db::name('customer')->where([['customer_name','like','%'.$customer_name.'%']])->column('id');
        }

        if ($shop_name) {
            $shopIds     = Db::name('shop')->where([['shop_name','like','%'.$shop_name.'%']])->column('shop_id');
            $userIds1     = Db::name('customer')->where([['shop_id','in',$shopIds]])->column('id');
            $userIds     = empty($userIds) ? $userIds1 : array_merge($userIds,$userIds1);
        }
        if ($market_id) {
            $shopIds     = Db::name('shop')->where([['market_id','=',$market_id]])->column('shop_id');
            $userIds2    = Db::name('customer')->where([['shop_id','in',$shopIds]])->column('id');
            $userIds     = empty($userIds) ? $userIds2 : array_merge($userIds,$userIds2);
        }
        if (!empty($userIds)) {
            array_push($where,['customer_id','in',$userIds]);
        }else if(empty($userIds) && ($customer_name || $shop_name || $market_id)){
            array_push($where,['customer_id','=',-1]);
        }
        // ['shop_name','market_name']
        // 读取列表 //
        // 获取的参数 //
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        if($shopIds){
            $userIds2 = Db::name('customer')->where([['shop_id','in',$shopIds]])->column('id');
            array_push($where,['customer_id','in',$userIds2]);
        }
        // array_push($where,['shop_id','in',$shopIds]);
        $dataCount  = Db::name('coupon_provide_customer')->alias('cs')
                    ->join('coupon c', 'cs.coupon_id=c.id', 'LEFT')
                    ->where($where)
                    ->count();
        $field = 'cs.id,cs.customer_id,cs.coupon_id,cs.create_time,cs.use_time,cs.order_id,cs.order_sn,c.name,c.type,c.denomination,c.use_threshold,cs.user_id';
        $list  = Db::name('coupon_provide_customer')->alias('cs')
                    ->join('coupon c', 'cs.coupon_id=c.id', 'LEFT')
                    ->field($field)
                    ->where($where)
                    ->limit(($page - 1) * $limit, $limit)->order('cs.id DESC')->select()->toArray();
        if($list)
        {
            $customer_ids    = array_values(array_unique(array_column($list, 'customer_id')));
            $customerList    = Db::name('customer')->where('id','in',$customer_ids)->column(['customer_name','shop_id'],'id');
            $shopIds         = array_values(array_unique(array_column($customerList, 'shop_id')));
            $shopList        = Db::name('shop')->where('shop_id','in',$shopIds)->column(['shop_name','shop_id','market_name'],'shop_id');
            $userIds         = array_values(array_unique(array_column($list, 'user_id')));
            $userList        = Db::name('admin_user')->where('id','in',$userIds)->column(['realname'],'id');
// print_r($shopList);
            //获取客户的相关数据
            foreach ($list as &$v) {
              $v['create_time']     = $v['create_time'] ? date('Y-m-d', $v['create_time']) : '';
              $v['use_time']        = $v['use_time'] ? date('Y-m-d', $v['use_time']) : '';
              $v['shop_name']       = $shopList[$customerList[$v['customer_id']]['shop_id']]['shop_name'] ?? '';
              $v['market_name']     = $shopList[$customerList[$v['customer_id']]['shop_id']]['market_name'] ?? '';
              $v['customer_name']   = $customerList[$v['customer_id']]['customer_name'];
              $v['user_name']       = $userList[$v['user_id']] ?? '';
              if ($v['type'] == 1) {
                  $v['type']        = '满减券';
              }else if ($v['type'] == 3) {
                  $v['type']        = '满赠券';
              }else{
                  $v['type']        = '兑换券';
              }
            }
        }
        $data              = [];
        $data['list']      = $list ?? [];
        $data['dataCount'] = $dataCount ?? 0;
        return resultArray(['data' => $data]);
    }

    /***
     * 获取优惠券的核销记录
     */
    public function getWriteOff_export()
    {
        $request = $this->param;
        // 获取需要的搜索参数 //
        // $page  = $request['page'] ?? 1;
        // $limit = $request['limit'] ?? 15;
        // $customer_name = $request['customer_name'] ?? 0;
        // $shop_name     = $request['shop_name'] ?? 0;
        // $market_id     = $request['market_id'] ?? 0;

        // // 设置搜索条件 //
        $where = [];

        // $userIds = [];
        // if ($customer_name) {
        //     // array_push($where,['customer_id','=',$customer_id]);
        //     $userIds     = Db::name('customer')->where([['customer_name','like','%'.$customer_name.'%']])->column('id');
        // }

        // if ($shop_name) {
        //     $shopIds     = Db::name('shop')->where([['shop_name','like','%'.$shop_name.'%']])->column('shop_id');
        //     $userIds1     = Db::name('customer')->where([['shop_id','in',$shopIds]])->column('id');
        //     $userIds     = empty($userIds) ? $userIds1 : array_merge($userIds,$userIds1);
        // }
        // if ($market_id) {
        //     $shopIds     = Db::name('shop')->where([['market_id','=',$market_id]])->column('shop_id');
        //     $userIds2    = Db::name('customer')->where([['shop_id','in',$shopIds]])->column('id');
        //     $userIds     = empty($userIds) ? $userIds2 : array_merge($userIds,$userIds2);
        // }
        // if (!empty($userIds)) {
        //     array_push($where,['customer_id','in',$userIds]);
        // }else if(empty($userIds) && ($customer_name || $shop_name || $market_id)){
        //     array_push($where,['customer_id','=',-1]);
        // }
        // // ['shop_name','market_name']
        // // 读取列表 //
        // // print_r($where);exit();
        // // 获取的参数 //

            $ids = $request['id'] ?? [];
            array_push($where,['id','in',$ids]);
        $dataCount  = Db::name('coupon_provide_customer')->alias('cs')
                    ->join('coupon c', 'cs.coupon_id=c.id', 'LEFT')
                    ->where($where)
                    ->count();
        $field = 'cs.id,cs.customer_id,cs.coupon_id,cs.create_time,cs.use_time,cs.order_id,cs.order_sn,c.name,c.type,c.denomination,c.use_threshold,cs.user_id';
        $list  = Db::name('coupon_provide_customer')->alias('cs')
                    ->join('coupon c', 'cs.coupon_id=c.id', 'LEFT')
                    ->field($field)
                    ->where($where)->order('cs.id DESC')->select()->toArray();
        if($list)
        {
            $customer_ids    = array_values(array_unique(array_column($list, 'customer_id')));
            $customerList    = Db::name('customer')->where('id','in',$customer_ids)->column(['customer_name','shop_id'],'id');
            $shopIds         = array_values(array_unique(array_column($customerList, 'shop_id')));
            $shopList        = Db::name('shop')->where('shop_id','in',$shopIds)->column(['shop_name','shop_id','market_name'],'shop_id');
            $userIds         = array_values(array_unique(array_column($list, 'user_id')));
            $userList        = Db::name('admin_user')->where('id','in',$userIds)->column(['realname'],'id');
// print_r($shopList);
            //获取客户的相关数据
            foreach ($list as &$v) {
              $v['create_time']     = $v['create_time'] ? date('Y-m-d', $v['create_time']) : '';
              $v['use_time']        = $v['use_time'] ? date('Y-m-d', $v['use_time']) : '';
              $v['shop_name']       = $shopList[$customerList[$v['customer_id']]['shop_id']]['shop_name'] ?? '';
              $v['market_name']     = $shopList[$customerList[$v['customer_id']]['shop_id']]['market_name'] ?? '';
              $v['customer_name']   = $customerList[$v['customer_id']]['customer_name'];
              $v['user_name']       = $userList[$v['user_id']] ?? '';
              if ($v['type'] == 1) {
                  $v['type']        = '满减券';
              }else if ($v['type'] == 2) {
                  $v['type']        = '满赠券';
              }else{
                  $v['type']        = '兑换券';
              }
            }
        }
        $callName = [
            'order_sn' => '订单编号',
            'customer_name' =>'客户名称',
            '' =>'核销人',
            'shop_name' => '店铺名称',
            'market_name' => '市场名称',
            'renameason' => '优惠券名称',
            'use_threshold' => '使用规则',
            'reason' => '面值',
            'create_time' => '领取时间',
            'use_time' => '使用时间',
            ];
        // print_r($callName);exit;
        $downUrl = exportExcelData('list',$callName,$list,'xlsx',1);
        return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
    }

    public function get_number_of_prompts(ReturnVistT $ReturnVistT): json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['userInfo'] = $this->userInfo;
        $this->param['shopIds'] = $shopIds;
        $data = $ReturnVistT->getNumberOfPrompts($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVistT->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 获取标签列表
     */
    public function read_member_label(Setting $setting): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $setting->read_member_label($this->param);
        if (!$data) {
            return resultArray(['error' => $setting->getError()]);
        }
        return resultArray(['data' => $data]);
    }


    /**
     * 新增标签
     */
    public function add_member_label(Setting $setting): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $setting->add_member_label($this->param);
        if (!$data) {
            return resultArray(['error' => $setting->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 新增标签
     */
    public function read_member_label_info(Setting $setting): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $setting->read_member_label_info($this->param);
        if (!$data) {
            return resultArray(['error' => $setting->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 编辑标签
     */
    public function save_member_label(Setting $setting): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $setting->save_member_label($this->param);
        if (!$data) {
            return resultArray(['error' => $setting->getError()]);
        }
        return resultArray(['data' => $data,'error'=>'编辑成功']);
    }

    /**
     * 获取二级标签接口
    */
    public function getTwoLabel(Setting $setting): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $setting->getTwoLabel($this->param);
        // if (!$data) {
        //     return resultArray(['error' => $setting->getError()]);
        // }
        return resultArray(['data' => $data,'error'=>'获取成功']);
    }

    /**
     * 相册列表
     */
    public function albumList(CustomerModel $CustomerModel): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $CustomerModel->albumList($this->param);
        // // if (!$data) {
        // //     return resultArray(['error' => $setting->getError()]);
        // // }
        return resultArray(['data' => $data,'error'=>'获取成功']);
    }

    /**
     * 新增相片
     */
    public function addAlbum(CustomerModel $CustomerModel): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $CustomerModel->addAlbum($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerModel->getError()]);
        }
        return resultArray(['data' => [],'error' => $CustomerModel->getError()]);
    }

    /**
     * 删除相片
     */
    public function deleteAlbum(CustomerModel $CustomerModel): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $CustomerModel->deleteAlbum($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerModel->getError()]);
        }
        return resultArray(['data' => [],'error'=>$CustomerModel->getError()]);
    }

    /**
     * 删除案例治疗记录照片
     */
    public function deleteCaseLogImg(CustomerModel $CustomerModel): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $CustomerModel->deleteCaseLogImg($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerModel->getError()]);
        }
        return resultArray(['data' => [],'error'=>$CustomerModel->getError()]);
    }

    /***
     *关闭服务
     */
    public function gbservice(Service $Service): Json
    {
        try{
            $this->param['user_id'] = $this->userInfo['id'];
            $data = $Service->gbservice($this->param);
            return resultArray(['data'=>$data,'error'=>'操作成功']);
        }catch (\Exception $e){
            return resultArray(['error'=>$e->getMessage()]);
        }


    }

	/***
	 *删除服务记录
	 */
	public function delservicelog(Service $Service): Json
	{

	    $this->param['user_id'] = $this->userInfo['id'];
        $this->param['shop_person_id'] = $this->userInfo['shop_person_id'];
	    $data = $Service->delservicelog($this->param);
	    // print_r($data);exit;
	    return resultArray(['data'=>$data,'error'=>$Service->getError()]);
	}

    /***
     * 获取店铺列表
     */
    public function getTsShopList(): Json
    {
        $telephone = $this->param['telephone'] ?? 0;
        $shop_name = $this->param['shop_name'] ?? '';
        $cushopList = Db::name('customer')->where('telephone','=',$telephone)->column('shop_id');
        $where = [];
        array_push($where,['type','=',1]);
        array_push($where,['shop_type','=',2]);
        if($telephone){
            array_push($where,['shop_id','in',$cushopList]);
        }
        if($shop_name){
            array_push($where,['shop_name','like','%'.$shop_name.'%']);
        }
        $shopList = Db::name('shop')->where($where)->column('shop_id,shop_name');
        return resultArray(['data'=>$shopList,'error'=>'获取成功']);
    }

    /**
     * 处理直营店客户的余额数据
     */
    public function setZyCustomer()
    {

        // print_r(111111111111111111111);exit;
        $time = date('Ymd');
        $res = Db::name('customer_balance_tj')->where('time','=',$time)->find();
        if($res){
            return resultArray(['data'=>[],'error'=>'已被处理']);
        }
		$where = [];
		array_push($where,['type','=',1]);
		array_push($where,['shop_id','<>',73782774834649]);

        //$zyShopIds = Db::name('shop')->where('type','=',1)->column('shop_id');
		$zyShopIds = Db::name('shop')->where($where)->column('shop_id');
		/* echo '<pre>';
		print_r($zyShopIds); */
		//exit;

        // $zyCustomer = Db::name('customer')->where('shop_id','in',$zyShopIds)->column('customer_id');
        $zyB = Db::name('customer_balance')->where('shop_id','in',$zyShopIds)->column('customer_id,balance_category_id,money,complimentary_money,shop_id');
        $b = ['time'=>$time];
        array_walk($zyB, function(&$val, $key) use ($b) {
            $val = array_merge($val, $b);
        });
		/* echo count($zyB);
        print_r($zyB);exit; */
        $res = Db::name('customer_balance_tj')->insertAll($zyB);

        return resultArray(['data'=>[],'error'=>'处理成功']);
    }


    /**
     * 创建订单
     * @return Json
     * @author SL
     * @create 2021-06-03
     */
    public function createYhjOrder(): Json
    {
		$this->param = request()->param();

        // 获取数据
        // $this->param['operator_id']   = $this->param['nurse_id'] ?? 0;
        // $this->param['operator_name'] = $this->param['nurse_id'];
        // 获取优惠券数据
        // $data = [
        //         [
        //             'id'=>2,
        //             'is_project'=>0,
        //             'type'=>0,
        //             'start_time'=>'',
        //             'end_time'=>'',
        //             'num'=>'',
        //         ],[
        //             'id'=>3,
        //             'is_project'=>1,
        //             'type'=>1,
        //             'start_time'=>'2021-06-03 12:12',
        //             'end_time'=>'2021-06-03 12:12',
        //             'num'=>'3',
        //         ],[
        //             'id'=>4,
        //             'is_project'=>1,
        //             'type'=>1,
        //             'start_time'=>'',
        //             'end_time'=>'',
        //             'num'=>'3',
        //         ]
        //     ];
        $yhj_id     = $this->param['yhj_id'] ?? 0;
        $goods_list   = $this->param['goodsList'] ?? '';

		$incomeType     = $this->param['income_type'] ?? 0; //收入类型

        $customerYhj = Db::name('coupon_provide_customer')->where('id','=',$yhj_id)->find();
        if (empty($customerYhj)) {
            return resultArray(['error' => '优惠卷不存在']);
        }
        //获取优惠卷主表数据
        $yhjInfo = Db::name('coupon')->where('id','=',$customerYhj['coupon_id'])->find();
        if (empty($yhjInfo)) {
            return resultArray(['error' => '优惠卷不存在']);
        }
        //判断是否被使用
        if ($customerYhj['staus'] == 1) {
            return resultArray(['error' => '优惠券已被使用']);
        }
        if ($yhjInfo['type'] != 4) {
            return resultArray(['error' => '优惠券类型错误']);
        }
        // 判断是否过期
        $nowTime = time();
        if ($yhjInfo['start_time']>$nowTime) {
            // code...
            return resultArray(['error' => '优惠券未到兑换时间']);
        }
        if ($yhjInfo['end_time']<=$nowTime) {
            // code...
            return resultArray(['error' => '优惠券已过期']);
        }

        // 获取客户数据
        $customerTnfo = Db::name('customer')->where('id','=',$customerYhj['customer_id'])->find();
        // if ($customerTnfo['shop_id'] != $nurseInfo['shop_id']) {
        //     // code...
        //     return resultArray(['error' => '非本店客户，无法核销']);
        // }
        // 获取店铺数据
        $shopInfo = Db::name('shop')->where('shop_id','=',$customerTnfo['shop_id'])->find();
        $sshop_storeInfo = Db::name('shop_store')->where('id','=',$shopInfo['store_id'])->find();
        $shopInfo['store_kingdee_code'] = $sshop_storeInfo['kingdee_code'] ?? '';
        $nurse_id = $customerTnfo['nurse_id'];
        // 获取员工数据
        $nurseInfo = Db::name('shop_person')->where('id','=',$nurse_id)->find();
        if (empty($nurseInfo)) {
            // code...
            return resultArray(['error' => '员工信息不存在']);
        }
        // 获取订单商品数据
        $goodsIdArr = array_values(array_unique(array_column($goods_list,'id')));
        $sqlyhjGoodsList  = Db::name('shop_goods')->where('id','in',$goodsIdArr)->select()->toArray();
        $yhjGoodsList = [];
        foreach ($sqlyhjGoodsList as $key => $val){
            $yhjGoodsList[$val['id']] = $val;
        }
        // 验证
        $data = [
            'uid'               => $customerTnfo['id'], // 客户
            'consignee'         => $customerTnfo['customer_name'], // 收货人
            'order_no'          => $this->getOrderNo(), // 订单号
            'sale_id'           => $nurse_id, // 销售员id
            'sale_name'         => $nurseInfo['name'], // 销售员姓名
            'shop_id'           => $shopInfo['shop_id'], // 门店id
            'shop_name'         => trim($shopInfo['shop_name']), // 门店名称
            'operator_id'       => $nurseInfo['id'],//制单员id
            'operator_name'     => $nurseInfo['name'],//制单员姓名
            'create_time'       => time(), // 创建时间
            'deal_time'         => time(), // 成交日期
            'goods_price'       => 0, // 订单标准金额
            'total_amount'      => 0, // 订单总金额
            'pay_amount'        => 0, // 实收本金
            'discount_amount'   => 0, // 订单优惠金额
            'gift_amount'       => 0, // 实收赠金
            'order_amount'      => 0, // 订单优惠金额
            'is_experience'     => 0, // 是否体验 0否 1是
            'experience_id'     => 0, // 体验人id
            'experience_name'   => '', // 体验人姓名
            'is_outreach'       => 0, // 是否外联 0否 1是
            'coupon_id'         => $yhjInfo['id'], // 优惠券id
            'coupon_name'       => $yhjInfo['name'], // 优惠券id
            'outreahc_id'       => 0, // 外联人id
            'outreahc_name'     => '', // 外联人姓名
            'is_introduction'   => 0, // 是否转介绍 0否 1是
            'introduction_id'   => 0, // 转介绍人id
            'introduction_name' => '', // 转介绍人姓名
            'description'       => '', // 订单描述
            'order_type'        => 2, // 订单类型 1新单 2补单
            'business_type'     => 4, // 业务类型 1项目 2疤痕
			'income_type'       => $incomeType, // 收入类型 1服务（各类疗程卡项及疗程卡项赠送产品）2 产品销售（单独付费购买产品）3 医美收入
            'sales_policy'      => '', // 销售政策编码
            'market_id'         => $shopInfo['market_id'], // 市场id
            'market_name'       => $shopInfo['market_name'], // 市场名称
            'sales_organization'=> $shopInfo['market_kingdee_code'], // 销售组织编码
            'sales_name'        => $shopInfo['market_name'], // 销售组织名称
            'settlement_organization' => $shopInfo['market_kingdee_code'], // 结算组织编码
            'settlement_name'         => $shopInfo['market_name'], // 结算组织名称
            'delivery_name'       => $shopInfo['shop_name'], // 发货部门名称
            'delivery_king'       => $shopInfo['keycode'], // 发货部门编码
            'order_experience'        => 0 //订单是否有体验商品
        ];
        // print_r($data);exit;
        Db::startTrans();
        try {
            // if($yhj_id == 52){
            //     $orderId = 200;
            //     $member_products = 0;
            // }else{
                $orderId = Db::name('shop_order')->insertGetId($data);
            // }
            // $orderId = 200;
            // $member_products = 0;
            $orderGoodsList = [];
            $serviceDataAll = [];
            if ($orderId) {
                // print_r($yhjGoodsList);
                foreach ($goods_list as $k => $v) {
                    $thisGoods = $yhjGoodsList[$v['id']] ?? [];
                    if(empty($thisGoods)){
                        continue;
                    }
                    $oneArr = [];
                    $oneArr['order_id']     = $orderId;
                    $oneArr['create_time']  = time();
                    $oneArr['goods_id']     = $thisGoods['id'];
                    $oneArr['goods_name']   = $thisGoods['name'];
                    $oneArr['kingdee_code'] = $thisGoods['kingdee_code'];
                    $oneArr['goods_price']  = $thisGoods['goods_price'];
                    $oneArr['pay_price']    = 0;
                    $oneArr['spec_name']    = $thisGoods['spec_name'];
                    $oneArr['unit_code']    = $thisGoods['unit_code'];
                    $oneArr['unit_name']    = $thisGoods['unit_name'];
                    $oneArr['number']       = $v['number'];
                    $oneArr['desc']         = '';
                    $oneArr['is_project']   = $thisGoods['is_project'];//是否服务 1 是 2否
                    $oneArr['category_id']  = $thisGoods['category_id'];
                    $oneArr['is_coupon_goods'] = 1;//是否优惠券商品 0否 1是
                    $project_type = $v['project_type'] ?? 0;
                    $project_type = $project_type == 1 ?1:2;
                    $oneArr['project_type'] = $project_type;//服务类型 1 按次 2按天
                    $oneArr['service_number'] = isset($v['service_number']) ? $v['service_number'] : 0;//服务次数
                    $oneArr['start_time']     = isset($v['start_time']) ? strtotime($v['start_time']) : 0;
                    $oneArr['end_time'] = isset($v['end_time']) ? strtotime($v['end_time']) : 0;
                    $oneArr['is_gift']  = 1;
                    $oneArr['house_code'] = $shopInfo['store_kingdee_code'];
                    $oneArr['coupon_type'] = 4;//优惠券类型
                    $oneArr['house_code_name'] = $shopInfo['market_name'];
                    // print_r($v);
                    array_push($orderGoodsList,$oneArr);
                    if($v['is_project'] == 2 && $v['id'] != 170 && $v['id'] != 171){
                        for($i=1;$i<=$orderGoodsList[$k]['number'];$i++){
                            $oneService['name']    = $oneArr['goods_name'];  //服务名称
                            $oneService['num']     = $oneArr['service_number'];   // 必填--服务类型：1按期2按次
                            $oneService['shop_id'] = $data['shop_id'];    // 店铺id
                            $oneService['customer_id']  = $data['uid'];   // 必填--客户id
                            $oneService['service_type'] = $oneArr['project_type']==1?2:1;   // 必填--服务类型：1按期2按次
                            $oneService['start_time']   = $oneArr['start_time'];    // 类型为1是必填--服务开始时间
                            $oneService['end_time']     = $oneArr['end_time'];      // 类型为1是必填--服务开始时间
                            $oneService['experience']   = $data['is_experience'];     // 0否1是 是否体验
                            $oneService['kk_user_id']   = $data['sale_id'];     // 开卡人id
                            $oneService['kk_money']     = $data['total_amount'];       // 开卡金额
                            $oneService['goods_id']     = $oneArr['goods_id'];       // 开卡金额
                            $oneService['category_id']  = $oneArr['category_id'];       // 开卡金额
                            array_push($serviceDataAll,$oneService);
                        }
                    }
                }
            }else{
                return resultArray(['error' => '核销失败']);
            }
            // if($yhj_id == 52){
            //     // print_r($orderGoodsList);exit;
            // }
            // print_r($orderGoodsList);exit;
            Db::name('shop_order_goods')->insertAll($orderGoodsList);

                //添加操作记录
                // $goods_name = array_column($orderGoodsList, 'goods_name');
                // $goods_name_str = implode('|', $goods_name);
                // $content = '创建订单：【'. $nurseInfo['name'] . '】创建了【' . $customerTnfo['customer_name'] . '】' . '的订单，订单号：【' . $data['order_no'] . '】，商品：【' . $goods_name_str . '】';
                // $code = [];
                // $code = $data;
                // $code['orderGoodsList']  = $orderGoodsList;
                // $this->addActionRecord($nurseInfo['id'],'shop_order_create',$orderId,$content,'shop','order',json_encode($code));
                // 处理客户的余额 //
                $customerModel = new \app\crm\model\Customer();
                $customer_id   = $data['uid'];    // 客户的id
                $balanceData   = [                // 余额变更数据集
                    // 'change_type'  => 2,      // 变动类型 1:增加 2:减少
                    // 'change_money' => $data['pay_amount'],      // 变更的本金
                    // 'complimentary_money' => $data['gift_amount'],  // 变更的赠金
                    // 'balance_category_id' => $data['business_type'] // 变更的余额的类型 1:疤痕 2:项目
                    ];
                $newOrderData  = [   // 新单变更数据集
                    // 'cj_time'  => ($data['type']==3 && $data['order_type']==1 && $total_amount>500)?$data['deal_time']:0,     // 成交时间-时间戳
                    // 'cj_money'    => $total_amount,    // 成交金额
                    // 'cj_order_id' => $orderId, // 成交的订单单号
                    ];
                $orderInfo     = [       // 本次需要新增的订单金额
                    // 'order_amount' => $total_amount, // 本次订单金额
                    // 'order_time'   => $data['deal_time'],   // 本次订单的时间-时间戳
                ];
                $member_products = 0; // 购买了几次会员商品
                $yhjOrderInfo  = [    // 本次需要处理的优惠卷
                    'yhj_id'     => $yhj_id??0,      // 本次优惠卷的id
                    'order_id'  => $orderId,   // 本次订单的id
                    'order_no'  => $data['order_no'],   // 本次订单的id
                    'operator_id' => $data['sale_id'],  // 核销人的id
                ];
                $customerModel->processingFunds($customer_id,$balanceData,$deal_time=0,$newOrderData,$orderInfo,$yhjOrderInfo,$member_products);
                // print_r($serviceDataAll);exit;
                $customerModel->addCustomService($customer_id,$serviceDataAll);
                //处理成功，推送金蝶
                // exit;
                // 处理客户的余额 //
                // 客户推送金蝶
                if ($shopInfo['type'] != 2)
                {
                    $res = $customerModel->pushKingCustomer($customer_id);
                    if($res == false){
                        $error = $customerModel->getError();
                        return resultArray(['error' => $error]);
                    }
                    $kingDee = new Kingdee();
                    $result=$kingDee->send_order($orderId);
                    if ($result['code'])
                    {
                        $error = $result['msg'];
                        return resultArray(['error' => $error]);
                    }
                }
                Db::commit();
                $error = '创建成功';
                return resultArray(['data'=>[],'error' => $error]);
                // return true;
        }catch (\Exception $e) {
                Db::rollback();
                $error = $e->getMessage();
                // print_r($error);
                // return false;
        }
        return resultArray(['error' => $error]);
        // if (empty($orderGoodsList)) {
        //     // code...
        //     return resultArray(['error' => '无法获取商品数据，无法进行核销']);
        // }
        // Db::name('shop_order_goods')->insertAll($orderGoodsList);

        //     // 添加操作记录
        //     $goods_name = array_column($orderGoodsList, 'goods_name');
        //     $goods_name_str = implode('|', $goods_name);
        //     $content = '创建订单：【'. $operator_name . '】创建了【' . $request['consignee'] . '】' . '的订单，订单号：【' . $data['order_no'] . '】，商品：【' . $goods_name_str . '】';
        //     $code = [];
        //     $code = $data;
        //     $code['orderGoodsList']  = $orderGoodsList;
        //     $this->addActionRecord($request['operator_id'],'shop_order_create',$orderId,$content,'shop','order',json_encode($code));
        //     // 处理客户的余额 //
        //     $customerModel = new \app\crm\model\Customer();
        //     $customer_id   = $data['uid'];    // 客户的id
        //     $balanceData   = [                // 余额变更数据集
        //         'change_type'  => 2,      // 变动类型 1:增加 2:减少
        //         'change_money' => $data['pay_amount'],      // 变更的本金
        //         'complimentary_money' => $data['gift_amount'],  // 变更的赠金
        //         'balance_category_id' => $data['business_type'] // 变更的余额的类型 1:疤痕 2:项目
        //         ];
        //     $newOrderData  = [   // 新单变更数据集
        //         // 'cj_time'  => ($data['type']==3 && $data['order_type']==1 && $total_amount>500)?$data['deal_time']:0,     // 成交时间-时间戳
        //         // 'cj_money'    => $total_amount,    // 成交金额
        //         // 'cj_order_id' => $orderId, // 成交的订单单号
        //         ];
        //     $orderInfo     = [       // 本次需要新增的订单金额
        //         // 'order_amount' => $total_amount, // 本次订单金额
        //         // 'order_time'   => $data['deal_time'],   // 本次订单的时间-时间戳
        //     ];
        //     // $member_products = 0; // 购买了几次会员商品
        //     $yhjOrderInfo  = [    // 本次需要处理的优惠卷
        //         'yhj_id '     => isset($request['yhj_id'])?$request['yhj_id']:0,      // 本次优惠卷的id
        //         'order_id  '  => $orderId,   // 本次订单的id
        //         'order_no  '  => $data['order_no'],   // 本次订单的id
        //         'operator_id' => $data['sale_id'],  // 核销人的id
        //     ];
        //     $customerModel->processingFunds($customer_id,$balanceData,$newOrderData,$orderInfo,$yhjOrderInfo,$member_products);
        //     // print_r($serviceDataAll);exit;
        //     $customerModel->addCustomService($customer_id,$serviceDataAll);
        //     //处理成功，推送金蝶
        //     // exit;
        //     // 处理客户的余额 //
        //     // 客户推送金蝶
        //     if ($shop['type'] == 1)
        //     {
        //     $res = $customerModel->pushKingCustomer($customer_id);
        //     if($res == false){
        //         $this->error = $customerModel->getError();
        //         return false;
        //     }
        //         $kingDee = new Kingdee();
        //         $result=$kingDee->send_order($orderId);
        //         if ($result['code'])
        //         {
        //             $this->error = $result['msg'];
        //             return false;
        //         }
        //     }
        //     Db::commit();
        //     $this->error = '创建成功';
        //     return true;
    }

    /**
     * 生成订单号
     * @param  array $request 请求参数
     * @return String
     * @author SL
     * @create 2021-06-03
     */
    public function getOrderNo()
    {
        $order_sn = null;
        // 保证不会有重复订单号存在
        while(true){
            $order_sn = date('YmdHis').rand(1000,9999); // 订单编号
            $order_sn_count = DB::name('shop_order')->where('order_no', $order_sn)->count();
            if($order_sn_count == 0)
                break;
        }
        return $order_sn;
    }


    /**
     * 员工预约列表
     * @param  SysModelMini $SysModelMini
     * @return Json
     */
    public function staffBooksList(SysModelMini $sysModelMini): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $sysModelMini->getStaffBookList($this->param);
        if (!$data) {
            return resultArray(['error' => $transferShop->getError()]);
        }
        return resultArray(['data' => $data]);
    }


    /**
     * 获取黄v数据
     */
    public function getYellowV()
    {
        $customer  = new CustomerModel();

        $data = $customer->getYellowV($this->param);

        return resultArray(['data' => $data]);


    }
    /**
     * 黄v客服详情页数据
     */
    public function getYellowVService()
    {
        $customer  = new CustomerModel();

        $data = $customer->getYellowVService($this->param);

        return resultArray(['data' => $data]);



    }
    /**
     * 黄v护理师详情页
     */
    public function getYellowVPhysician()
    {
        $customer  = new CustomerModel();

        $data = $customer->getYellowVPhysician($this->param);

        return resultArray(['data' => $data]);

    }

    /**
     * 预约列表
     *
     * @return Json
     */

    public function staffBooksList2()
    {
        $param = request()->param();
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $shopIds = [];
        array_push($shopIds,$param['shop_id']);
        $where = [];
        $startTime = strtotime($param['time']);
        if(empty($startTime))
        {
            $startTime = strtotime(date('Y-m-d'));
        }
        $endTime = $startTime+24*60*60-1;
        array_push($where,['b.yy_time','between',[$startTime,$endTime]]);
        array_push($where,['b.status','=',0]);
		array_push($where,['a.status','=',1]);
        if(!empty($shopIds))
        {
            array_push($where,['a.shop_id','in',$shopIds]);
        }
        $result = Db::name("shop_person")->alias('a')
            ->join("books b",'b.shop_person_id = a.id','left')
            ->join("customer c","b.customer_id = c.id",'left')
            ->field('b.yy_time,b.yy_time_str,b.shop_person_id,b.is_use,a.name as person_name,c.id,c.telephone,c.customer_name')
            ->where($where)
            ->select()->toArray();

        // var_dump($result);die;

        $person = array_column($result,'shop_person_id');
        $where = [];
        array_push($where,['id','not in',$person]);
		array_push($where,['status','=',1]);


        if(!empty($shopIds))
        {
            array_push($where,['shop_id','in',$shopIds]);
        }
        $result2 = Db::name("shop_person")
            ->field('id as shop_person_id,name as person_name')
            ->where($where)
            ->select()->toArray();

        foreach ($result2 as $key => $value)
        {
            $result2[$key]['type']=1;
        }
        $result=array_merge($result,$result2);

        $data = [];
        $times = [];

        $shop_type = Db::name('shop')->where('shop_id',$param['shop_id'])->value('shop_type');

        if($shop_type == 1){

            $time_interval = 3600;

        }else{

            $time_interval = 1800;

        }
        for ($now = strtotime(date('Y-m-d')." 9:00");$now<=strtotime(date('Y-m-d')." 20:00");$now+=$time_interval)
        {
            array_push($times,date('H:i',$now));
        }

        // var_dump($result);die;

        foreach ($result as $key => $value)
        {
            if(empty($data[$value['shop_person_id']]))
            {
                $data[$value['shop_person_id']] = [
                    'person_name' => $value['person_name'],
                    'shop_person_id' => $value['shop_person_id'],
                ];

                $distribution = [];
                for ($now = strtotime(date('Y-m-d')." 9:00"); $now <= strtotime(date('Y-m-d')." 20:00"); $now += $time_interval)
                {
                    $distribution[] = [
                        "time" => date('H:i', $now),
                        "status" => 2, // 默认状态为2（未预约）
                        "customer" => []  // 初始化空的客户数组
                    ];
                }
                if(!empty($value['type']))
                {
                    $data[$value['shop_person_id']]['distribution'] = $distribution;
                    continue;
                }
            } else {
                $distribution = $data[$value['shop_person_id']]['distribution'];
            }

            $time = explode(',', $value['yy_time_str']);
            if(empty($time))
            {
                $data[$value['shop_person_id']]['distribution'] = $distribution;
                continue;
            }

            foreach ($time as $timeSlot)
            {
                $timeIndex = (strtotime($param['time']." ".$timeSlot) - strtotime($param['time']." "."09:00")) / $time_interval;

                // 确保索引在有效范围内
                if(isset($distribution[$timeIndex]))
                {
                    // 检查客户名称是否为空
                    $customerName = $value['customer_name'] . $value['telephone'];

                    // 只添加非空的客户记录
                    if(!empty($customerName)) {
                        // 修复点1：不再清空客户数组，而是追加新客户
                        $customerInfo = [
                            'id' => $value['id'],
                            'name' => $customerName,
                            'status' => $value['is_use']
                        ];

                        // 修复点2：检查是否已存在相同客户，避免重复添加
                        $customerExists = false;
                        foreach ($distribution[$timeIndex]['customer'] as $existingCustomer) {
                            if ($existingCustomer['name'] === $customerInfo['name']) {
                                $customerExists = true;
                                break;
                            }
                        }

                        if (!$customerExists) {
                            $distribution[$timeIndex]['customer'][] = $customerInfo;
                        }

                        // 修复点3：状态更新为有预约 (0/1) 而不是总是覆盖
                        // 只有当原状态是未预约(2)时才更新状态
                        if ($distribution[$timeIndex]['status'] == 2) {
                            $distribution[$timeIndex]['status'] = $value['is_use'];
                        }
                    }
                }
            }

            $data[$value['shop_person_id']]['distribution'] = $distribution;
        }

        // 格式化输出结果
        foreach ($data as $personId => &$personData)
        {
            foreach ($personData['distribution'] as &$slot)
            {
                // 保留空的customer数组，不删除
                // if(empty($slot['customer'])) {
                //     unset($slot['customer']);
                // }
            }
            unset($slot);
        }
        unset($personData);

        $data = array_merge($data, []);
        return $this->success(['data' => $data, 'times' => $times], "获取完成", count($data));
    }


    public function personcustomerList()
    {
        $param = request()->param();
        $personId = $param['person_id']??0;
        if(empty($personId))
        {
            return $this->failed(400,"参数错误");
        }
        $person  = PersonModel::find($personId);
        if(!$person)
        {
            return $this->failed(400,"参数错误");
        }
        $customer = new \app\crm\model\Customer();
        $where = [];
        array_push($where,['shop_id','=',$person->shop_id]);
//        array_push($where,['customer_name','like',"%".$param['name']."%"]);
        $customer = $customer->where($where)->field('id,customer_name,telephone')->select()->toArray();
        return $this->success($customer);
    }

    /**
     * 添加预约
     *
     * @return mixed
     */
    public function submitBooks()
    {
        $param = request()->param();
        $personId = $param['person_id']??0;
        $person  = PersonModel::find($personId);
        $params = [
            'shop_person_id'=>$personId,
            'customer_id'=>$param['customer_id'],
            'shop_id'=>$person->shop_id,
        ];
        if(empty($param['date']))
        {
            $params['yy_year']=date('Y');
            $params['yy_date']=date('m-d');
            $date = date('Y-m-d');
        }else{
            $dateStr = strtotime($param['date']);
            $params['yy_year']=date('Y',$dateStr);
            $params['yy_date']=date('m-d',$dateStr);
            $date = $param['date'];
        }
        $startTime = strtotime($date.$param['start_time']);
        $endTime = strtotime($date.$param['end_time']);
        $time = [];
        for ($now = $startTime;$now<=$endTime;$now+=30*60)
        {
            array_push($time,date('H:i',$now));
        }
        $params['yy_time']=$time;
        $model = new SysModelMiniCustomer();


        $data = $model->addYYData2($params,$this->app);

        return resultArray(['error' => '获取成功', 'data' => $data]);

    }

    /**
     * 获取预约记录id
     *
     * @return Json
     */
    public function getBookId()
    {
        $param = request()->param();
        if(empty($param['date']))
        {
            $date = date('Y-m-d');
        }else{
            $date = $param['date'];
        }
        $startTime = strtotime($date);
        $endTime = strtotime($date)+24*60*60;
        $where = [];
        array_push($where,['shop_person_id','=',$param['person_id']]);
        array_push($where,['customer_id','=',$param['customer_id']]);
        array_push($where,['yy_time','>=',$startTime]);
        array_push($where,['yy_time','<',$endTime]);
        array_push($where,['yy_time_str','like','%'.$param['start_time'].'%']);
        array_push($where,['cancel_time','=',0]);
        // $book = Db::name('books')->where($where)->find();
        $book = Db::name('books')
            ->field([
                'id',
                'customer_id',
                'shop_person_id',
                'shop_id',
                'FROM_UNIXTIME(yy_time, "%Y") AS yy_year',
                'FROM_UNIXTIME(yy_time, "%m-%d") AS yy_date',
                'yy_time_str'
            ])
            ->where($where)
            ->find();
        return $this->success(['data'=>$book]);

    }

    /**
     * 取消预约
     * @return mixed
     */
    public function cancelBook()
    {
        $param = request()->param();

        $params = [
            'bookId'=>$param['book_id'],
            'person'=>$this->userInfo['id'],
            'platform'=>2,
            'yy_time'=>""
        ];
        $time = Db::name('books')->where('id','=',$param['book_id'])->value('yy_time');
        $times = Db::name('books')->where('id','=',$param['book_id'])->value('yy_time_str');
        $times = explode(',',$times);
        if(!empty($times))
        {
            $params['yy_time']=$times[0].'-'.$times[count($times)-1];
        }
        $date = date('Y-m-d',$time);
        $params['yy_date']=$date;
        $model = new SysModelMiniCustomer();

        $data = $model->cancelBook($params,$this->app);
        if($data['data'] == '已取消'){
            return resultArray(['error' => '已取消,请勿重复预约']);
        }else{
            return resultArray(['error' => '操作成功', 'data' => $data]);
        }
    }

    /**
     * 客户标签统计
     *
     * @return Json
     */
    public function getTagCount()
    {
        $param = request()->param();
        $tagGroupName = $param['tag_group_name']??"";
        $result = Db::name('customer')->group('member_label')->column('count(*) as count,member_label');
        $data = [];
        foreach ($result as $value)
        {
            if (!empty($value['member_label']))
            {
                $tags = explode(',',$value['member_label']);
                foreach ($tags as $v)
                {
                    if(empty($data[$v]))
                    {
                        $data[$v]=[
                            'member_label'=>$v,
                            'count'=>0
                        ];
                    }
                    $data[$v]['count']+=$value['count'];
                }
            }
        }
//        $setting = Db::name('setting')->alias('a')
//            ->join('setting b','a.id = b.pid')
//            ->field('a.id,a.name,a.status,b.name as tag_group_name')
//            ->where([
//                ['a.category_id','=',7],
//                ['a.pid','<>',0]
//            ])
//            ->select()->toArray();
        $setting=Db::query("select a.id,a.name,a.status,b.name as tag_group_name from xy_setting as a,xy_setting as b where a.pid = b.id and a.pid <> 0 and a.category_id = 7 and b.name like :name ", ['name'=>'%'.$tagGroupName.'%']);
        foreach ($setting as $key =>$value)
        {
//            if(empty($data[$value['id']]['count']))
//            {
//                unset($setting[$key]);
//                continue;
//            }
            $setting[$key]['count']=$data[$value['id']]['count']??0;
            if($value['status']==1)
            {
                $setting[$key]['status']="启用";
            }else{
                $setting[$key]['status']="禁用";

            }
        }
        $setting = array_merge($setting,[]);
        return $this->success($setting,"获取完成",count($setting));
    }

    public function addHealPlan()
    {
        $param = request()->param();

        $healId = $param['healId'] ?? '';
        $customer_id = $param['customer_id'] ?? '';

        $heal_date = $param['heal_date'] ?? '';

        if(!$heal_date){
            return resultArray(['error' => "清选择就诊日期！"]);
        }

        $time = time();

        if($healId){
            $save = [
                'text1' => $param['text1'],
                'text2' => $param['text2'],
                'text3' => $param['text3'],
                'text4' => $param['text4'],
                'text5' => $param['text5'],
                'text6' => $param['text6'],
                'text7' => $param['text7'],
                'text8' => $param['text8'],
                'text9' => implode(',',$param['text9']),
                'text10' => $param['text10'],
                'text11' => $param['text11'],
                'text12' => $param['text12'],
                'heal_plan' =>  $param['heal_plan'],
                'customer_name' => $param['customer_name'],
                'customer_sex' => $param['customer_sex'],
                'customer_birthday' => strtotime($param['customer_birthday']),
                'update_time' => $time,
            ];

            Db::name('customer_healplan')->where('id','=',$healId)->update($save);

            return resultArray(['error' => '更新成功', 'data' => []]);

        }else{
            $addData = [
                'customer_id' => $customer_id,
                'heal_date' => strtotime($heal_date),
                'doctor' => $param['doctor'],
                'heal_number' => $param['doctor'],
                'text1' => $param['text1'],
                'text2' => $param['text2'],
                'text3' => $param['text3'],
                'text4' => $param['text4'],
                'text5' => $param['text5'],
                'text6' => $param['text6'],
                'text7' => $param['text7'],
                'text8' => $param['text8'],
                'text9' => implode(',',$param['text9']),
                'text10' => $param['text10'],
                'text11' => $param['text11'],
                'text12' => $param['text12'],
                'heal_plan' =>  $param['heal_plan'],
                'customer_name' => $param['customer_name'],
                'customer_sex' => $param['customer_sex'],
                'customer_birthday' => strtotime($param['customer_birthday']),
                'create_time' => $time,
                'update_time' => $time,
            ];



            $id = Db::name('customer_healplan')->insertGetId($addData);

            if($id){
                return resultArray(['error' => '添加成功', 'id' => $id]);
            }else{
                return resultArray(['error' => '添加失败', 'id' => $id]);
            }
        }




    }

    public function getHealPlan()
    {
        $param = request()->param();

        $customer_id = $param['customer_id'] ?? '';

        if(!$customer_id){
            return resultArray(['error' => "!!!"]);
        }

        $healPlan = Db::name('customer_healplan')->where('customer_id',$customer_id)->find();


        if($healPlan){
            $healPlan['heal_date'] = date("Y-m-d",$healPlan['heal_date']);
            $healPlan['customer_birthday'] = date("Y-m-d",$healPlan['customer_birthday']);

            if($healPlan['text9']){

                $text9 = explode(',',$healPlan['text9']);

                $one = [];
                foreach ($text9 as $key => $value) {
                    array_push($one,intval($value));
                }

                $healPlan['text9'] = $one;

            }

            return resultArray(['error' => '', 'data' => $healPlan]);
        }else{
            return resultArray(['error' => '', 'data' => []]);
        }


    }


    //小程序显示客户余额
    public function showBalance(){
        $param = request()->param();
        $shop_id = $this->userInfo['shop_id'];
        $res = true;
        if(!empty($shop_id)){
            if(in_array($param['type'],[1,2])){
                $update['is_show_balance'] = $param['type']  == 1?0:1;
                $update['update_time'] = time();
                $res = Db::name('customer')->where('shop_id',$shop_id)->update($update);
            }
        }
        if(!$res){
            return resultArray(['error' => '操作失败，请稍后重试']);
        }
        return resultArray(['error' => '操作成功', 'data'=>[]]);
    }


    /**
     * 顾客预存货列表
     */
    public function prestockList(): json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $customer  = new CustomerModel();

        $data = $customer->prestockList($this->param);

        return resultArray(['data' => $data]);
    }

    /**
     * 顾客账户列表
     */
    public function accountLogList(): json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $CustomerAccountLog  = new CustomerAccountLog();

        $data = $CustomerAccountLog->getAccountLog($this->param);

        return resultArray(['data' => $data]);
    }

    /**
     * 手机号变更记录
     */
    public function phoneLogList(): json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $CustomerModel  = new CustomerModel();

        $data = $CustomerModel->getPhoneChangeLog($this->param);

        return resultArray(['data' => $data]);
    }

    /**
     * 主治医师+所属护士变更记录
     */
    public function changeLogList(): json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $CustomerModel  = new CustomerModel();

        $data = $CustomerModel->getChangeLogList($this->param);

        return resultArray(['data' => $data]);
    }

    //统计有哪些营销中心转店的用户没有补充资料
    public function transferList(): json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $CustomerModel  = new CustomerModel();

        $data = $CustomerModel->getTransferList($this->param);

        return resultArray(['data' => $data]);
    }

    /**
     * 用户资产剩余
     */
    public function surplusAccountCount(): json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $CustomerModel  = new CustomerModel();

        $data = $CustomerModel->getSurplusAccountCount($this->param);

        return resultArray(['data' => $data]);
    }







}
